package com.zmx;

import com.zmx.core.dto.RequestLogInfo;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @ClassName: test1
 * @Author zhaomxr
 * @Date 2021-12-24 10:19
 */
@Slf4j
public class test1 {

    public static void main(String[] args) throws InterruptedException {
        RequestLogInfo requestLogInfo = new RequestLogInfo();
        requestLogInfo.setPointer(-1);
        requestLogInfo.setRows(4);
        getLog(requestLogInfo);
    }

    public static void getLog(RequestLogInfo requestLogInfo) throws InterruptedException {
        System.out.println("pointer:" + requestLogInfo.toString());

        while (true){
            RequestLogInfo result = randomRed(requestLogInfo);
            requestLogInfo.setPointer(result.getPointer());

            if(result.getContent() != null && result.getContent().size() > 0){
                for(String s:result.getContent()){
                    System.out.println(s);
                }
            }

            Thread.sleep(10);
        }



    }

    /**
     * 读取文件
     **/
    public static RequestLogInfo randomRed(RequestLogInfo requestLogInfo) {
        List<String> logInfo = new ArrayList<String>(16);
        try {
            String path = "/logs/execute/mall-job-execute.log";
            long pointer = requestLogInfo.getPointer();
            long rows = requestLogInfo.getRows() < 0 ? 10 : requestLogInfo.getRows();

            File file = new File(path);
            if (file == null) {
                System.out.println("文件不存在");
                return requestLogInfo;
            }

            RandomAccessFile raf = new RandomAccessFile(file, "r");
            if (pointer <= -1) {
                pointer = raf.length() - 1;
                rows = 100;
            }

            while (rows > 0) {
                //移动文件指针位置
                raf.seek(pointer);
                String line = null;
                //循环读取
                while ((line = raf.readLine()) != null) {
                    if (line.equals("")) {
                        continue;
                    }
                    //打印读取的内容,并将字节转为字符串输入，做转码处理，要不然中文会乱码
                    line = new String(line.getBytes("ISO-8859-1"), "UTF-8");
                    logInfo.add(line);
                }

                rows--;
                //文件读取完毕后，将文件指针游标设置为当前指针位置
                pointer = raf.getFilePointer();
            }

            requestLogInfo.setContent(logInfo);
            requestLogInfo.setPointer(pointer);
        } catch (Exception e) {
            log.error("读取日志异常：" + e.getMessage(), e);
        }

        return requestLogInfo;
    }
}
